#!/usr/bin/env bash

PARENT_DIR=$1
if [ -z "$PARENT_DIR" ];
then
    PARENT_DIR=~/
fi
pushd "$PARENT_DIR" > /dev/null
PARENT_DIR=`pwd`
popd > /dev/null

TARGET_DIR_NAME=dotfiles-hotdox
TARGET_DIR=$PARENT_DIR/$TARGET_DIR_NAME

if [ -f "$TARGET_DIR" ];
then
    TARGET_DIR_MOVED=${TARGET_DIR}.file.old
    echo "moving existing file \"$TARGET_DIR\" to \"$TARGET_DIR_MOVED\""
    mv "$TARGET_DIR" "$TARGET_DIR_MOVED"
fi

TARGET_REPOSITORY="https://dotfiles-hotdox.googlecode.com/svn/trunk"

if [ -d "$TARGET_DIR" ];
then
    REPOSITORY=`svn info "$TARGET_DIR" | grep '^URL:' | sed 's/^URL: *//'`
    if [ "$REPOSITORY" != "$TARGET_REPOSITORY" ];
    then
        TARGET_DIR_MOVED=${TARGET_DIR}.dir.old
        echo "moving existing dir \"$TARGET_DIR\" to \"$TARGET_DIR_MOVED\""
        mv "$TARGET_DIR" "$TARGET_DIR_MOVED"
    fi
fi

TARGET_USER="whalebot.helmsman@gmail.com"
UPDATE_TIMESTAMP_FILE_NAME=timestamp
UPDATE_TIMESTAMP_FILE=$TARGET_DIR/$UPDATE_TIMESTAMP_FILE_NAME
if [ ! -d "$TARGET_DIR" ];
then
    svn co "$TARGET_REPOSITORY" "$TARGET_DIR" --username "$TARGET_USER" --trust-server-cert --non-interactive
    date +%s > $UPDATE_TIMESTAMP_FILE
    echo "0" >> $UPDATE_TIMESTAMP_FILE
fi

pushd "$TARGET_DIR" > /dev/null
TARGET_DIR=`pwd`
popd > /dev/null

NOW=`date +%s`
DAY_LENGTH_IN_SECONDS=`echo "60 * 60 * 24" | bc`
TIME_SINCE_LAST_UPDATE=`echo "$DAY_LENGTH_IN_SECONDS + 1" | bc`
if [ -f "$UPDATE_TIMESTAMP_FILE" ];
then
    LAST_UPDATE=`head -n 1 "$UPDATE_TIMESTAMP_FILE"`
    TIME_SINCE_LAST_UPDATE=`echo "$NOW - $LAST_UPDATE" | bc`
fi

if [ "$TIME_SINCE_LAST_UPDATE" -gt "$DAY_LENGTH_IN_SECONDS" ];
then
    echo "update \"$TARGET_DIR_NAME\""
    svn up "$TARGET_DIR"
    echo "$NOW" > $UPDATE_TIMESTAMP_FILE
fi

LINKER_SCRIPT=$TARGET_DIR/bash/linker.sh
if [ -f "$LINKER_SCRIPT" ];
then
    source "$LINKER_SCRIPT" "$PARENT_DIR" "$TARGET_DIR"
else
    echo "error: linker script missing"
fi

BASHRC=$PARENT_DIR/.bashrc
if [ ! -e "$BASHRC" ];
then
    touch "$BASHRC"
fi

CALL_STRING="source $TARGET_DIR/bash/rc.sh $PARENT_DIR $TARGET_DIR"
FIND_CALL_STRING=`grep "$CALL_STRING" "$BASHRC" || true`
if [ -z "$FIND_CALL_STRING" ];
then
    echo "$CALL_STRING" >> $BASHRC
fi

CHANGES=`svn stat "$TARGET_DIR"`
if [ -n "$CHANGES" ];
then
    echo "changes in \"$TARGET_DIR\" do not forget to commit"
    echo "$CHANGES"
fi

